<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/29
 * Time: 14:00
 */
namespace app\api\controller\v1;

use app\api\service\OrderService;
use app\api\validate\OrderPlace;
use app\api\validate\PaginParmter;
use think\Controller;
use app\api\service\Token as TokenService;
use app\api\model\Order as OrderModel;

class Order extends Controller {

    /**
     * 用户在选择商品后，向API提交包含它所选择商品的相关信息
     * API在接收到商品信息后，需要检查相关商品的库存量
     * 有库存，把订单数据存入数据库中，下单成功，返回客户端，告诉客户可以支付了
     * 调用支付接口进行支付
     * 还需要再次进行库存量检测
     * 服务器这边就可以调用微信的支付接口
     * 微信服务器会返回一个支付结果
     * 成功：也需要进行库存检测
     * 成功：库存量的扣除
     */
    protected $beforeActionList = [
        'first' => ['only'=>'placeorder,getsummarybyuser']
    ];

    public function first(){
//        print_r(date('Ymd').OrderService::buildOrderID());
//        print_r(json_encode($this->products));
    }

    public function placeOrder(){
        (new OrderPlace())->goCheck();
        $oProducts = input('post.products/a');
        $uid = TokenService::getCurrentUid();
        $orderServcie = new OrderService();
        $result = $orderServcie->place($uid,$oProducts);
        if($result['order_id'] == -1){
            return json(['code'=>404,'msg'=>'商品库存不足','data'=>$result]);
        }
        return json(['code'=>200,'msg'=>'OK','data'=>$result]);
    }


    public function getSummaryByUser($page = 1,$limit = 5){
        (new PaginParmter())->goCheck();
        $uid = TokenService::getCurrentUid();
        $pagingOrders = OrderModel::getSummaryByUser($uid,$page,$limit);
//        print_r($pagingOrders);die;
        if($pagingOrders->isEmpty()){
            return json($pagingOrders->toArray());
        }
        return json($pagingOrders->toArray());
    }
}